<template style="background-color: #f6f6f6">

  <el-card class="box-card" >

    <template #header>
      <div class="card-header">
        <span>会议室管理</span>
        <span style="float: right;">
            <el-input
                style="float: left;width: 200px;"
                v-model="search"
                size="default"
                placeholder="输入关键字搜索"/>
            <el-select v-model="currentUniId"
                       :disabled="false"
                       style="width: 250px;"
                       @change="initTable"
            >
              <el-option
                  v-for="uni in universityList"
                  :key="uni.id"
                  :label="uni.name"
                  :value="uni.id"/>
            </el-select>
            <el-button @click="initUniversity"><el-icon><Refresh /></el-icon></el-button>
            <el-button type="primary" plain @click="openAddDialog(true)">创建会议室</el-button>
          </span>
      </div>
    </template>

    <div style="height: 90%">
      <el-table v-loading="tableLoading"
                row-key="id"
                :data="filterData"
                style="width: 100%; height:90%"
                border stripe >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="num" label="会议室号" width="200" align="center"/>
        <el-table-column prop="location" label="会议室地址" align="center"/>
        <el-table-column prop="seatLimit" label="座位上限" width="200" align="center"/>
        <el-table-column prop="rowNum" label="座位行数" width="200" align="center"/>
        <el-table-column prop="colNum" label="座位列数" width="200" align="center"/>
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)">座位排布</el-button>
            <el-button size="small" type="primary" @click="openAddDialog(false,scope.row)">复制会议室</el-button>
            <el-button size="small" type="danger" @click="deleteRoom(scope.row.id)">删除会议室</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :small="true"
          :disabled="false"
          :background="true"
          layout="prev, pager, next"
          @change="initTable"
          v-model:current-page="current"
          :page-count="pageCount"
      />

    </div>

  </el-card>

  <el-dialog
      v-model="editDialogVisible"
      title="座位排布"
      width="55%"
      align-center>

    <div class="container">
      <!-- 输入参数部分 -->
      <div class="input-section">
        <label style="margin-right: 50px">
          行数：
          <el-input-number v-model.number="rows" :min="1" :max="20"  placeholder="行数" />
        </label>
        <label>
          列数：
          <el-input-number v-model.number="cols" :min="1" :max="20"  placeholder="行数" />
        </label>
      </div>

      <div style="margin-inline: auto;margin-bottom: 20px;border: 2px solid #00d2ff;width: 200px">
        讲台
      </div>

      <!-- 方块显示区域 -->
      <div
          class="grid-container"
          :style="{
        '--cols': cols,
        '--cell-size': '30px',
        'grid-template-rows': `repeat(${rows}, var(--cell-size))`
      }"
      >
        <div
            v-for="(row, rowIndex) in grid"
            :key="rowIndex"
            class="row"
        >
          <div
              v-for="(cell, colIndex) in row"
              :key="colIndex"
              class="cell"
              :class="{
                selected: cell.selected,
                highlightBlue: isSelecting && isHighLighting(rowIndex, colIndex)===2,
                highlightRed: isSelecting && isHighLighting(rowIndex, colIndex)===1
              }"
              @click="handleCellClick(rowIndex, colIndex)"
              @mouseenter="handleCellMouseEnter(rowIndex, colIndex)"
          >
            {{ cell.selected ? '' : '' }}
            <el-icon v-if="cell.selected"><UserFilled /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
              v-loading.fullscreen.lock="editLoading"
              type="primary" @click="submitSeat">
            确认
          </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="addDialogVisible"
      title="编辑会议室信息"
      width="40%"
      align-center>

    <el-form :model="form" label-width="100px">
      <el-form-item label="会议室号">
        <el-input v-model="form.num" style="width: 450px;"/>
      </el-form-item>
      <el-form-item label="座位排布">
        <el-button type="primary" @click="editDialogVisible = true">进入座位排布</el-button>
      </el-form-item>
      <el-form-item label="会议室地址">
        <el-input
            v-model="form.location"
            style="width: 450px"
            :rows="3"
            type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
              v-loading.fullscreen.lock="addLoading"
              type="primary" @click="submitRoom">
            确认
          </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script >

import moment from 'moment';
import { ElMessage } from 'element-plus'
import {Edit, Plus, Refresh} from "@element-plus/icons-vue";
import university from "@/view/university/index.vue";
export default {
  components: {Plus, Edit, Refresh},
  data(){
    return{
      file:'',
      current:1,
      currentPage:1,
      pageCount:0,
      dataId:'',
      tableData:[],
      universityList: [],
      currentUniId: '',
      tableLoading:false,
      editLoading:false,
      addLoading:false,
      search:'',
      addDialogVisible:false,
      editDialogVisible:false,
      isAddSeat:false,
      form:{
        id:'',
        uniId:'',
        num:'',
        location:'',
        seatLimit:'',
        rowNum:'',
        colNum:'',
        seatId:''
      },
      currentSeatId:'',
      currentRoomId:'',
      rows: 1,
      cols: 1,
      grid: [],
      startRow: null,
      startCol: null,
      endRow: null,
      endCol: null,
      isSelecting: false
    }
  },
  computed:{
    filterData(){
      return this.tableData.filter((data) => {
        return !this.search || data.name!=null&&data.name.toLowerCase().includes(this.search.toLowerCase())||data.id===this.search;
      });
    },
    selectedCells() {
      return this.grid.flat().filter(cell => cell.selected);
    }
  },
  watch: {
    rows(newVal) {
      this.validateAndInit(newVal, this.cols);
    },
    cols(newVal) {
      this.validateAndInit(this.rows, newVal);
    }
  },
  created() {
    this.validateAndInit(this.rows, this.cols);
  },
  methods : {
    validateAndInit(rows, cols) {
      this.rows = Math.max(rows, 1);
      this.cols = Math.max(cols, 1);
      this.initGrid(this.grid);
      this.resetSelection();
    },
    initGrid(grid) {
      this.grid = Array.from({ length: this.rows }, (_, rowIndex) => {
        return Array.from({ length: this.cols }, (_, colIndex) => ({
          selected: rowIndex+1>grid.length?false:colIndex+1>grid[rowIndex].length?false:grid[rowIndex][colIndex].selected,
          row: rowIndex + 1,
          col: colIndex + 1
        }));
      });
    },
    handleCellClick(rowIndex, colIndex) {
      if (!this.isSelecting) {
        // 第一次点击：记录起点
        this.startRow = rowIndex;
        this.startCol = colIndex;
        this.endRow = rowIndex;
        this.endCol = colIndex;
        this.isSelecting = true;
      } else {
        // 第二次点击：记录终点并选区
        this.endRow = rowIndex;
        this.endCol = colIndex;
        this.selectRegion();
        this.resetSelection();
      }
    },
    handleCellMouseEnter(rowIndex, colIndex) {
      console.log(rowIndex, colIndex);
      if (this.isSelecting) {
        this.endRow=rowIndex;
        this.endCol=colIndex;
      }
    },
    selectRegion() {
      // 计算矩形区域的边界
      const minRow = Math.min(this.startRow, this.endRow);
      const maxRow = Math.max(this.startRow, this.endRow);
      const minCol = Math.min(this.startCol, this.endCol);
      const maxCol = Math.max(this.startCol, this.endCol);
      // 遍历区域内的所有单元格并选中
      for (let row = minRow; row <= maxRow; row++) {
        for (let col = minCol; col <= maxCol; col++) {
          this.grid[row][col].selected = !this.grid[row][col].selected;
        }
      }
    },
    resetSelection() {
      this.startRow = null;
      this.startCol = null;
      this.endRow = null;
      this.endCol = null;
      this.isSelecting = false;
    },
    isInRange(row, col) {
      // 高亮显示选区过程中的区域
      if (!this.isSelecting) return false;
      const minRow = Math.min(this.startRow, this.endRow);
      const maxRow = Math.max(this.startRow, this.endRow);
      const minCol = Math.min(this.startCol, this.endCol);
      const maxCol = Math.max(this.startCol, this.endCol);
      return (
          row >= minRow && row <= maxRow &&
          col >= minCol && col <= maxCol
      );
    },
    isHighLighting(row, col){
      if(this.isInRange(row, col)){
        return this.grid[row][col].selected?1:2;
      }
      else 0;
    },
    openEditDialog(info){
      this.isAddSeat=false;
      this.currentRoomId=info.id;
      this.currentSeatId=info.seatId;
      this.editLoading=true;
      this.$http.get("/meeting/room/seat?seatId="+this.currentSeatId)
          .then((response) => {
            if(response.data.code===200){
              const tempGrid=response.data.data.grid;
              this.cols=response.data.data.colNum;
              this.rows=response.data.data.rowNum;
              const grid=[];
              for (let i = 0; i < tempGrid.length; i++) {
                grid[i]=[];
                for (let j = 0; j < tempGrid[i].length; j++) {
                  grid[i][j]={
                    row: i+1,
                    col: j+1,
                    selected: tempGrid[i][j]
                  }
                }
              }
              this.initGrid(grid);
              this.editDialogVisible=true;
              this.editLoading=false;
            }
            else {
              this.cols=info.colNum;
              this.rows=info.rowNum;
              this.editDialogVisible=true;
              this.editLoading=false;
            }
      });
      this.editLoading=false;
    },
    submitSeat(){
      if(this.isAddSeat){
        this.editDialogVisible=false;
        return;
      }
      //console.log(this.grid);
      //return;
      this.editLoading=true;
      const seatGrid = [];
      for (let i = 0; i < this.rows; i++) {
        const row = [];
        for (let j = 0; j < this.cols; j++) {
          row.push(this.grid[i][j].selected);
        }
        seatGrid.push(row);
      }
      this.$http.put("/meeting/room/update/seat",{
        id: this.currentSeatId,
        roomId: this.currentRoomId,
        grid: seatGrid,
        rowNum: this.rows,
        colNum: this.cols
      }).then((response) => {
        console.log(response);
        if(response.data.code===200){
          ElMessage({
            message: '座位信息修改成功',
            type: 'success'
          });
          this.editDialogVisible=false;
          this.editLoading=false;
        }
        else {
          ElMessage.error(response.data.msg);
        }
      });
      this.editLoading=false;
    },
    submitRoom(){
      this.addLoading=true;
      const seatGrid = [];
      for (let i = 0; i < this.rows; i++) {
        const row = [];
        for (let j = 0; j < this.cols; j++) {
          row.push(this.grid[i][j].selected);
        }
        seatGrid.push(row);
      }
      this.$http.post("/meeting/room/add",{
        grid: seatGrid,
        rowNum: this.rows,
        colNum: this.cols,
        uniId:this.currentUniId,
        location:this.form.location,
        num:this.form.num
      }).then((response) => {
        console.log(response);
        if(response.data.code===200){
          ElMessage({
            message: '添加成功',
            type: 'success'
          });
          this.initTable();
          this.addDialogVisible=false;
          this.addLoading=false;
        }
        else {
          ElMessage.error(response.data.msg);
        }
      });
      this.addLoading=false;
    },
    openAddDialog(isNew,info){
      this.isAddSeat=true;
      if(isNew){
        this.addDialogVisible=true;
        this.grid=[];
        this.initGrid(this.grid);
        this.rows=1;
        this.cols=1;
        this.form={};
        return;
      }
      this.form=info;
      this.$http.get("/meeting/room/seat?seatId="+this.form.seatId)
          .then((response) => {
            if(response.data.code===200){
              const tempGrid=response.data.data.grid;
              this.cols=response.data.data.colNum;
              this.rows=response.data.data.rowNum;
              const grid=[];
              for (let i = 0; i < tempGrid.length; i++) {
                grid[i]=[];
                for (let j = 0; j < tempGrid[i].length; j++) {
                  grid[i][j]={
                    row: i+1,
                    col: j+1,
                    selected: tempGrid[i][j]
                  }
                }
              }
              this.initGrid(grid);
              this.addDialogVisible=true;
              this.addLoading=false;
            }
            else {
              this.cols=info.colNum;
              this.rows=info.rowNum;
              this.addDialogVisible=true;
              this.addLoading=false;
            }
          });
      this.addDialogVisible=true;
    },
    deleteRoom(id){
      const idList=[];
      idList.push(id);
      this.$http.delete("/meeting/room?idList="+idList
      ).then((response) => {
        if(response.data.code===200){
          this.initTable();
          ElMessage({
            message: '删除成功',
            type: 'success'
          });
        }
      });
    },
    initUniversity(){
      this.tableLoading=true;
      this.$http.get("/user/university/list",{
        page: 1,
        size: 10,
        sortFieId: 'id',
        isASC: 'true'
      }).then((response) => {
        console.log(response);
        if(response.data.code===200){
          this.universityList=response.data.data.records;
          this.currentUniId=response.data.data.records[0].id;
          this.initTable();
          this.tableLoading=false;
        }
      });
      this.tableLoading=false;
    },
    initTable(){
      this.tableLoading=true;
      this.$http.get("/meeting/room/select?uniId="+this.currentUniId+"&college="+this.currentCollege+"&page="+this.current+"&size=12&sortFieId=id&isASC=true")
          .then((response) => {
        console.log(response);
        if(response.data.code===200){
          this.tableData=response.data.data.records;
          this.pageCount=response.data.data.pages;
          this.tableLoading=false;
        }
      });
      this.tableLoading=false;
    }
  },
  mounted(){
    this.initUniversity();
  }
}
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  height: 94%;
}
.container {
  margin-right: 50px;
  margin-left: 50px;
  padding: 20px;

  .input-section {
    gap: 20px;
    margin: auto;
    margin-bottom: 20px;
  }

  .grid-container {
    margin-inline: auto;
    display: grid;
    gap: 2px;
    grid-template-columns: repeat(var(--cols), var(--cell-size));
  }

  .row {
    display: contents; /* 使子元素直接参与外层 grid 布局 */
  }

  .cell {
    width: var(--cell-size);
    height: var(--cell-size);
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
  }

  .cell.selected {
    background-color: #4CAF50;
    color: white;
  }

  .selected-info {
    margin-top: 20px;
    padding: 10px;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
  }

  .selected-info h3 {
    margin: 0 0 10px;
  }

  .cell.highlightBlue {
    border: 1px solid #2196F3; /* 蓝色边框表示选区 */
  }

  .cell.highlightRed {
    border: 1px solid #f44336; /* 蓝色边框表示选区 */
  }

}
</style>